package com.helen.mybatis.parse;

import com.google.common.collect.Maps;
import com.helen.mybatis.configration.Configuration;
import com.helen.mybatis.configration.MappedStatement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @author helenlee
 * @date 2020/4/8
 */
public class XmlConfigurationBuilder {
    public static void build(Configuration configuration,InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(inputStream);
        Element rootElement = document.getRootElement();
        // property
        List<Element> propertys = rootElement.selectNodes("/configuration/dataSource/property");

        Properties properties = new Properties();
        propertys.forEach(node -> properties.setProperty(node.attributeValue("name"), node.attributeValue("value")));

        DataSource dataSource = new ComboPooledDataSource();
        ((ComboPooledDataSource) dataSource).setDriverClass(properties.getProperty("driver"));
        ((ComboPooledDataSource) dataSource).setJdbcUrl(properties.getProperty("url"));
        ((ComboPooledDataSource) dataSource).setUser(properties.getProperty("username"));
        ((ComboPooledDataSource) dataSource).setPassword(properties.getProperty("password"));
        configuration.setDataSource(dataSource);
        // 加载驱动
        Class.forName(properties.getProperty("driver"));


        Map<String,MappedStatement> mappedStatementMap = Maps.newHashMap();
        configuration.setMappedStatementMap(mappedStatementMap);

        // mapper
        List<Element> mappers = rootElement.selectNodes("/configuration/mappers/mapper");
        for (Element mapper : mappers) {
            String resource = mapper.attributeValue("resource");
            XmlMappedStatementBuilder.build(configuration, resource);
        }
    }
}
